package net.xi.news.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xi.news.NotFoundException;
import net.xi.news.dao.TypeMapper;
import net.xi.news.pojo.Type;
import net.xi.news.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper,Type> implements TypeService {


    @Autowired
    private TypeMapper typeRespository;


    @Override
    //根据分类名得到分类
    public Type getTypeByName(String name) {
        Map<String,Object> map=new HashMap<>();
        map.put("name",name);
        List<Type> types = typeRespository.selectByMap(map);
        if (types!=null&&types.size()!=0){
            return types.get(0);
        }
        return null;
    }


    @Transactional
    @Override
    //更新分类
    public Integer updateType(String id, Type type) {
        Type type1 = typeRespository.selectById(id);
        if (type1 == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,type1);
        return typeRespository.insert(type1);
    }

    @Override
    //列出前？分类
    public List<Type> typeTop(Integer size) {
        Page<Type> page=new Page<>();
        page.setSize(size);
        Page<Type> page1 = typeRespository.selectPage(page, null);
        return page1.getRecords();
    }


    public String getTypeByCode(){
//      第一次查询缓存全部

        return null;
    }

}
